package main

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

var conf *AppConfig
var RunPath string
var p string = string(os.PathSeparator)

type AppConfig struct {
	Host string `json:"host"`

	SrcPath string `json:"src"`
	OutPath string `json:"out"`

	Signer   CmdConfig `json:"signer"`
	ZipAlign CmdConfig `json:"zipAlign"`
}

type CmdConfig struct {
	Name        string   `json:"name"`
	Args        []string `json:"args"`
	Encoding    string   `json:"encoding"`
	SuccessFlag string   `json:"success"`
}

func LoadConfig() {
	conf = &AppConfig{}
	var bytes []byte
	var err error

	bytes, err = ioutil.ReadFile(getConfigFile())

	if err == nil {
		json.Unmarshal(bytes, conf)
	}
}

func getConfigFile() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	paths := strings.Split(path, p)
	fileName := p + paths[len(paths)-1]
	newFileName := p + "app.conf"
	RunPath = strings.Replace(path, fileName, p, 1)
	path = strings.Replace(path, fileName, newFileName, 1)
	return path
}
